package com.eqdd.yiqidian.ui.mine.shenqing.fragment;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;

import com.eqdd.yiqidian.CoolRefreshRecyclerViewFragmentCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.BaseFragment;
import com.eqdd.yiqidian.base.CommonTabFragment;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.CommonTabBean;
import com.eqdd.yiqidian.bean.rebuild.FragmentBean;
import com.eqdd.yiqidian.bean.rebuild.LayoutMapBean;
import com.eqdd.yiqidian.bean.rebuild.ListResultBean;
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource;
import com.eqdd.yiqidian.helper.mvchelper.Rx2DataSource;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.utils.DateUtil;
import com.eqdd.yiqidian.utils.GreenDaoUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okrx2.adapter.FlowableBody;
import com.shizhefei.mvc.MVCCoolHelper;

import org.reactivestreams.Publisher;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;

/**
 * Created by lvzhihao on 17-7-19.
 */

public class MyCreateBaseFragment extends BaseFragment {
    CoolRefreshRecyclerViewFragmentCustom dataBinding;
    private SlimAdapterEx<FragmentBean> slimAdapterEx;
    private int status;
    private ModelRx2DataSource<FragmentBean> dataSource;
    private MVCCoolHelper<List<FragmentBean>> mvcHelper;
    private int pageNum = 0;
    private CommonTabBean commonTabBean;

    @Override
    protected void setView() {
        if (slimAdapterEx == null) {
            dataBinding.recyclerView.setSwipeItemClickListener((view, position) -> {
                Bundle bundle = new Bundle();
                bundle.putInt(Config.WHO, commonTabBean.getWho());
                bundle.putInt(Config.STATUS, status);
                bundle.putString(commonTabBean.getIdName(), slimAdapterEx.getData().get(position).getId() + "");
                ((BaseActivity) getActivity()).startActivityForResult(commonTabBean.getInfoActivity(), bundle, position);
            });
//            SwipeUtil.openSwipe(getActivity(), dataBinding.recyclerView, (menuBridge, pos) -> {
//                OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.DELETE_LEAVE)
//                        .params("userGuid", GreenDaoUtil.getUser().getGuid())
//                        .params("leaveId", slimAdapterEx.getDataItem(pos).getId())
//                        .execute(new DialogCallBack<HttpResult>((BaseActivity) getActivity()) {
//                            @Override
//                            public void onSuccess(Response<HttpResult> response) {
//                                HttpResult httpResult = response.body();
//                                ToastUtil.showShort(httpResult.getMsg());
//                                if (httpResult.getStatus() == 200) {
//                                    menuBridge.closeMenu();
//                                    slimAdapterEx.getData().remove(pos);
//                                    slimAdapterEx.notifyItemRemoved(pos);
//                                }
//                            }
//                        });
//            });
            dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            slimAdapterEx = SlimAdapterEx.create().registerDefault(commonTabBean.getLayoutId(), new SlimInjector<FragmentBean>() {
                @Override
                public void onInject(FragmentBean data, IViewInjector injector) {
                    try {
                        for (LayoutMapBean layoutMapBean : commonTabBean.getMapBeans()) {
                            if (layoutMapBean.getDealType() != 0) {
                                injector.text(layoutMapBean.getId(), getDeal(data, layoutMapBean.getDealType()));
                            } else {
                                String content = getString(data, layoutMapBean.getMethodName());
                                injector.text(layoutMapBean.getId(), layoutMapBean.isTime() ? DateUtil.format(content) : content);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).updateData(new ArrayList());
            dataSource = new ModelRx2DataSource<>(new ModelRx2DataSource.OnLoadSource() {
                @Override
                public Flowable<List> loadSourcce(int page, Rx2DataSource.DoneActionRegister register) {
                    return OkGo.<HttpResult<ListResultBean<FragmentBean>>>post(HttpConfig.BASE_URL + commonTabBean.getUrl())
                            .params("page", pageNum)
                            .params("companyId", GreenDaoUtil.getUser().getCompanyId())
                            .params("userGuid", GreenDaoUtil.getUser().getGuid())
                            .params("type", status)
                            .converter(new JsonConverter<HttpResult<ListResultBean<FragmentBean>>>() {
                                @Override
                                public void test() {
                                    super.test();
                                }
                            }).adapt(new FlowableBody<HttpResult<ListResultBean<FragmentBean>>>())
                            .flatMap(new Function<HttpResult<ListResultBean<FragmentBean>>, Publisher<List<FragmentBean>>>() {
                                @Override
                                public Publisher<List<FragmentBean>> apply(@NonNull HttpResult<ListResultBean<FragmentBean>> noticeWraperResultBeanHttpResult) throws Exception {
                                    pageNum = page == 1 ? 0 : noticeWraperResultBeanHttpResult.getItems().getPage();
                                    return Flowable.just(noticeWraperResultBeanHttpResult.getItems().getList() == null ? new ArrayList<FragmentBean>() : noticeWraperResultBeanHttpResult.getItems().getList());
                                }
                            });

                }
            });
            mvcHelper = new MVCCoolHelper<>(dataBinding.coolRefreshView);
            mvcHelper.setDataSource(dataSource);
            mvcHelper.setAdapter(slimAdapterEx);
            mvcHelper.refresh();
        }
    }

    private String getDeal(FragmentBean data, int dealType) {
        switch (dealType) {
            case 1:
                return data.getFour() + "-" + data.getFive();
            case 2:
                return "离职时间:" + data.getSeven();
            case 3:
                return "申请时间";
            case 4:
                return "调休时间";
            case 5:
                return DateUtil.format(data.getThird(), "MM-dd HH:mm") + " ~ " + DateUtil.format(data.getFour(), "MM-dd HH:mm");
            case 6:
                return "要消的迟到早退日期";
            case 7:
                return DateUtil.formatYMD(data.getFirst());
            case 8:
                return "要消的漏打卡日期";
        }
        return "";
    }

    private static String getString(Object o, String methodName) throws Exception {
        Method method = o.getClass().getMethod(methodName);
        return (String) method.invoke(o);
    }

    @Override
    protected void initData() {

        status = getArguments().getInt(Config.STATUS);
        commonTabBean = (CommonTabBean) getArguments().getSerializable("bean");
    }


    @Override
    public ViewDataBinding initBinding(LayoutInflater inflater) {
        return dataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_cool_recycler_view, null, false);

    }


    @Override
    public void onClick(View v) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Config.SUCCESS) {
            mvcHelper.refresh();
        }
    }
}
